<?php
class LoginController extends AppController {
    var $helpers = array ('Html','Form');
    var $name = 'Login'; // riferimento alla cartella delle view
    //var $modelClass = 'Multa';

    public function beforeFilter(){
    	
		parent::beforeFilter();
		
    	//It’s a handy place to check for an active session or inspect user permissions.
    	Controller::loadModel('User');
		
    }

    public function index() {

    }
	
	public function login() {
		
	}
	
	public function logout() {
		
	}
	
	public function entra() {
		
		if (!isset($this->request->data['login']) || $this->request->data['login']=='') {
			$this->Session->setFlash("Inserire Login!");
			// $this->redirect("/Login");
			$this->render("/Login/index");
		}
		$this->set('login',$this->request->data['login']);
		if (!isset($this->request->data['password']) || $this->request->data['password']=='') {
			$this->Session->setFlash("Inserire la password!");
			// $this->redirect("/Login");
			$this->render("/Login/index");
		}

		$ret = $this->User->find('all', array('fields' => array('User.USERNAME','Group.CODICE')
											   ,'conditions' => array('USERNAME' => $this->request->data['login'], 'PASSWORD' => $this->request->data['password'])
											   ,'recursive' => 2));

		if (isset($ret) && count($ret)>0) {
			// inserisco l'utente in sessione
			$group=$ret['0']['Group']['CODICE'];
			$this->Session->write("user", array('login' => $this->request->data['login'], 'group' => $group));
			if ($group=='ADM') {
				$this->redirect("/Multe");
			} else if ($group=='AGN') {
				$this->redirect("/Multe");
			} else if ($group=='MLT') {
				$this->redirect("/Multe/ricerca");
			} else {
				$this->Session->setFlash("L'utente non appartiene a nessun gruppo, contattare l'amministratore!");
				$this->esci();
			}
		} else {
			$this->Session->setFlash("Autenticazione fallita!");
			// $this->redirect("/Login");
			$this->render("/Login/index");
		}

	}
	
	public function esci() {
		$this->Session->delete("user");
		$this->Session->destroy;
		$this->redirect("/Login");
		
		
		
	}

}
?>